package com.easyCode.sqlBuilder.sqlInfo;
import com.easyCode.sqlBuilder.SqlInfo;
import lombok.Data;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Collectors;

/**
 * 负责提供构建表结构的相关sql信息
 *
 * @author 大忽悠
 * @create 2022/11/8 20:04
 */
@Data
public abstract class BaseTableSqlInfo implements SqlInfo {
    /**
     * 表名
     */
    protected String tableName;
    /**
     * 字段列表
     */
    protected List<BaseFiledSqlInfo> baseFiledSqlInfoList = new CopyOnWriteArrayList<>();
    /**
     * 索引列表
     */
    protected List<BaseKeySqlInfo> baseKeySqlInfoList = new CopyOnWriteArrayList<>();
    /**
     * 是否需要添加drop table的语句
     */
    protected Boolean dropTable=Boolean.TRUE;
    /**
     * 外键列表--便于检查
     */
    protected List<BaseKeySqlInfo> foreignKeyList=new CopyOnWriteArrayList<>();
    /**
     * 注释信息
     */
    protected String comment;

    @Override
    public String buildSql() {
        sortFiledList();
        return doBuildSql();
    }

    protected abstract String doBuildSql();

    /**
     * @return 如果没指定主键,那么返回空
     */
    public String getPrimaryKeyName() {
        List<BaseKeySqlInfo> primaryKey = baseKeySqlInfoList.stream().filter(BaseKeySqlInfo::isPrimary).collect(Collectors.toList());
        if(primaryKey.size()!=1){
            return null;
        }
        return (primaryKey.get(0)).getPrimaryKeyColumnName();
    }

    /**
     * 对表中字段按照字段优先级进行排序
     */
    private void sortFiledList() {
        baseFiledSqlInfoList.sort(Comparator.comparingInt(BaseFiledSqlInfo::getOrder));
    }

    public void addFiled(BaseFiledSqlInfo... toArray){
        this.baseFiledSqlInfoList.addAll(List.of(toArray));
    };

    public void addKey(BaseKeySqlInfo... toArray){
        this.baseKeySqlInfoList.addAll(List.of(toArray));
    };
}
